package face.pay.api.payter.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import face.pay.api.payter.service.IterminalLoginService;
import face.pay.constant.OrderType;
import face.pay.dao.*;
import face.pay.entity.*;
import face.pay.redis.RedisUtils;
import face.pay.util.ResultMessage;
import face.pay.util.bean.JavaBeanUtils;
import face.pay.util.msg.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: zkj
 * @Date: 2019/8/12 15:52
 * @Description:
 */
@Service
@Slf4j
public class TerminalLoginServceImpl implements IterminalLoginService {

    private static String TERMINA_LOGIN_PREFIX_KEY = "terminal:login_validateCode:";

    @Autowired
    private OemConfigInfoDao oemConfigInfoDao;

    @Autowired
    TerminalInfoDao terminalInfoDao;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    EnterpriseInfoDao enterpriseInfoDao;

    @Autowired
    StoreInfoDao storeInfoDao;

    @Autowired
    private UserInfoDao userInfoDao;

    @Override
    public ResultMessage login(String loginInfo) {

        log.info("设备登录:"+loginInfo);
        JSONObject info = JSON.parseObject(loginInfo);
        String deviceId = info.getString("device_id");
        String app_version =  info.getString("app_version");

        String validateCode = info.getString("validateCode");
        String imei = info.getString("imei");
        String sn = info.getString("sn");

        if (StringUtils.isNotBlank(deviceId) && StringUtils.isNotBlank(validateCode) && StringUtils.isNotBlank(imei)) {

            deviceId = deviceId.toUpperCase();

            TerminalInfo ter = this.terminalInfoDao.getByDeviceId(deviceId);
            Map map =  new HashMap();

            if (ter != null) {

                Integer storeId = ter.getStoreId();

                if(storeId!=null){

                     StoreInfo storeInfo =  this.storeInfoDao.getById(storeId);

                     EnterpriseInfo enterpriseInfo = this.enterpriseInfoDao.queryByUserId(ter.getUserId());

                     map.put("device_id",deviceId);
                     map.put("store_id",storeInfo.getId());
                     map.put("store_name",storeInfo.getName());
                     map.put("imei",imei);

                     String type = ter.getType();

                     if(OrderType.WECHAT.equals(type)){

                         if(StringUtils.isBlank(enterpriseInfo.getWxSubMchId())){
                             return ResultMessage.createFail("微信商户号未配置，拒绝登录");
                         }
                     }else if(OrderType.ALIPAY.equals(type)){
                         if(StringUtils.isBlank(enterpriseInfo.getAliUserId())){
                             return ResultMessage.createFail("支付宝商家账号未配置，拒绝登录");
                         }
                     }

                     if(deviceId.equals("DDD666")){

                        log.info("检测到测试号码 DDD666");

                        if("000000".equals(validateCode)){
                            ter.setImei(imei);
                            this.terminalInfoDao.update(ter);
                            return ResultMessage.createSuccess("登录成功",map);
                        }else {
                            return ResultMessage.createFail("验证码错误");
                        }

                    }

                    if(StringUtils.isBlank(ter.getImei()) || imei.equals(ter.getImei()) ){
                        String key = TERMINA_LOGIN_PREFIX_KEY + deviceId;

                        Object cache_validateCode = redisUtils.get(key);

                        if (cache_validateCode != null) {

                            if (validateCode.equals(cache_validateCode)) {

                                OemConfigInfo configInfo = oemConfigInfoDao.getByOemId(ter.getOemId());

                                map.put("appId",configInfo.getVoiceAppId());
                                map.put("appKey",configInfo.getVoiceAppKey());
                                map.put("secretKey",configInfo.getVoiceSecretKey());
                                if(StringUtils.isNotBlank(sn)){
                                    ter.setImei(sn);
                                }
                                ter.setImei(imei);


                                this.terminalInfoDao.update(ter);
                                return ResultMessage.createSuccess("登录成功",map);
                            }else {
                                log.info("验证码错误");
                                return ResultMessage.createFail("验证码错误");
                            }
                        }else {
                            log.info("验证码已失效");
                            return ResultMessage.createFail("验证码已失效");
                        }
                    }else {
                        log.info("该设备编码已在别的机器登录，请解绑");
                        return ResultMessage.createFail("该设备编码已在别的机器登录，请解绑");
                    }
                } else {
                    log.info("门店未绑定 登录失败");
                    return ResultMessage.createFail("门店未绑定 登录失败");
                }

            }else {
                    return  ResultMessage.createFail("登录失败，设备编码不存在");
            }

        } else {
            log.info("登录信息不全，登录拒绝");
            return ResultMessage.createFail("登录信息不全，登录拒绝");
        }

    }


    public ResultMessage getValidateCode(String validateCodeInfo) {
        log.info("设备获取验证码:"+validateCodeInfo);

        JSONObject info = JSON.parseObject(validateCodeInfo);
        String deviceId = info.getString("device_id");
        String imei = info.getString("imei");
        String version =  info.getString("app_version");


        deviceId = deviceId.toUpperCase();

        if(deviceId.equals("DDD666")){
            log.info("检测到测试号码 DDD666");
            return ResultMessage.createFail("测试号码验证码000000");
        }

        TerminalInfo ter = this.terminalInfoDao.getByDeviceId(deviceId);

        if (ter != null) {

            Integer oemId = ter.getOemId();

            Integer machUserId = ter.getUserId();

            OemConfigInfo configInfo = oemConfigInfoDao.getByOemId(oemId);

            UserInfo userInfo = this.userInfoDao.getById(machUserId);

            String mobile = userInfo.getMobile();

            String validateCode = JavaBeanUtils.generatesNumNonceStr(6);

            String key = TERMINA_LOGIN_PREFIX_KEY + deviceId;

            /**
             * 5 分钟
             */
            redisUtils.set(key,validateCode,300);
            JSONObject json = new JSONObject();
            json.put("code",validateCode);
            try {
                json.put("terminalCode",deviceId);


                SendSmsResponse sendSmsResponse =  SmsUtil.sendSms(mobile,configInfo.getSignName(),configInfo.getTerloginCode(),json.toString(),configInfo.getAccessKeyId(),configInfo.getAccessKeySecret());

                String code =    sendSmsResponse.getCode();
                String message =    sendSmsResponse.getMessage();

                log.info("message:"+message);
                if("OK".equals(code)&&"OK".equals(code)) {
                    log.info("验证码已发送");

                    return ResultMessage.createSuccess("验证码已经发送");
                }

            }catch (Exception e){
                log.error("验证码发送异常",e);
            }

        } else {
            return ResultMessage.createFail("设备编号错误");
        }

        return ResultMessage.createFail("获取验证码错误");
    }

    @Override
    public ResultMessage getInfo(String terminalInfo) {
        log.info("设备获取登录信息:"+terminalInfo);
        JSONObject info = JSON.parseObject(terminalInfo);
        String deviceId = info.getString("device_id");
        String app_version =  info.getString("app_version");

        String imei = info.getString("imei");

        if (StringUtils.isNotBlank(deviceId) &&  StringUtils.isNotBlank(imei)) {

            deviceId = deviceId.toUpperCase();

            TerminalInfo ter = this.terminalInfoDao.getByDeviceId(deviceId);
            Map map = new HashMap();

            if (ter != null) {

                Integer storeId = ter.getStoreId();

                if (storeId != null) {

                    StoreInfo storeInfo = this.storeInfoDao.getById(storeId);

                    EnterpriseInfo enterpriseInfo = this.enterpriseInfoDao.queryByUserId(ter.getUserId());

                    map.put("device_id", deviceId);
                    map.put("store_id", storeInfo.getId());
                    map.put("store_name", storeInfo.getName());
                    map.put("imei", imei);

                    String type = ter.getType();

                    /**
                     * 暂时取消imei 验证
                     */
                    if (StringUtils.isNotBlank(ter.getImei())) {

                        OemConfigInfo configInfo = oemConfigInfoDao.getByOemId(ter.getOemId());
                        map.put("appId", configInfo.getVoiceAppId());
                        map.put("appKey", configInfo.getVoiceAppKey());
                        map.put("secretKey", configInfo.getVoiceSecretKey());
                        return ResultMessage.createSuccess("获取信息成功", map);
                    } else {
                        log.info("设备信息验证失败");
                        return ResultMessage.createFail("设备信息验证失败");
                    }

                } else {
                    log.info("门店未绑定，获取信息失败");
                    return ResultMessage.createFail("门店未绑定，获取信息失败");
                }
            }else {
                log.info("设备编码不存在");
                return  ResultMessage.createSuccess("设备编码不存在");
            }
        }else {
            log.info("参数不全 获取信息失败");
            return  ResultMessage.createSuccess("参数不全 获取信息失败");
        }
    }
}
